<?php

class Config
{
	public static function getConfig($name, $app = null)
	{
		static $init = false;
		static $configs = array();

		$app = empty($app) ? APP_NAME : $app;

		if(isset($configs[$app][$name])) return $configs[$app][$name];
        
		$ac = ''; //app config class
		static $gc = ''; //global config class
		static $cc = 'CoreConfig'; //core config class
		
		$docRoot = rtrim(DOC_ROOT, '/,\\');
		$appcls = $docRoot . '/' . $app . '/config/'.strtolower($app).'.php';
		if(file_exists($appcls) && is_file($appcls))
		{
			require_once $appcls;
			$configClass = ucfirst(strtolower($app)).'Config';
			if(class_exists($configClass))
			{
			    $ims = class_implements($configClass);
			    if(in_array('AbstractConfig', $ims))
			    {
			        $ac = $configClass;
			    }
			}
		}
		if(!$init)
		{
		    $coreConfigClass = 'CoreConfig';
			$docRoot = rtrim(DOC_ROOT, '/,\\');
			$commoncls = $docRoot . '/Common/config/global.php';
			if(file_exists($commoncls) && is_file($commoncls))
			{
				require_once $commoncls;
				$globalConfigClass = 'GlobalConfig';
    			if(class_exists($globalConfigClass))
    			{
    			    $ims = class_implements($globalConfigClass);
    			    if(in_array('AbstractConfig', $ims))
    			    {
    			        $gc = $globalConfigClass;
    			    }
    			}
			}
		    if(!class_exists($cc))
			{
			    exit('Class '.$cc.' not exists!');
			}
			
			$init = true;
		}
		if($ac && call_user_func(array($ac, 'hasConfig'), $name))
		{
		    $configs[$app][$name] = call_user_func(array($ac, 'getConfig'), $name);
		}
		else if($gc && call_user_func(array($gc, 'hasConfig'), $name))
		{
			$configs[$app][$name] = call_user_func(array($gc, 'getConfig'), $name);
		}
		else if($cc && call_user_func(array($cc, 'hasConfig'), $name))
		{
			$configs[$app][$name] = call_user_func(array($cc, 'getConfig'), $name);
		}
		else 
		{
		    $configs[$app][$name] = null;
		}
		return $configs[$app][$name];
	}
}